<?php
/**
 * Created by PhpStorm.
 * User: Fenn
 * Date: 2018/7/11
 * Time: 6:28
 */

namespace App\Controllers;


use Slim\Http\Request;
use Slim\Http\Response;
use App\Transformers\UserTransformer;
use League\Fractal\Resource\Item;
use Respect\Validation\Validator as v;

class AuthController extends BaseController
{
    public function getCode(){

    }

    public function login(Request $request,Response $response,$args){

        $params = $request->getParams();

        $validation =  $this->validateRequest($params,$params['type']);
        //手机验证码登录
        if($params['type']==1){
            if($validation->failed()){
                return $this->json(-101,'手机号码或者是验证码错误');
            }
            $user = $this->container->auth->attempt($params['phone'],$params['code'],$params['type']);
        }else if($params['type']==2){ //账号密码登录
            if($validation->failed()){
                return $this->json(-102,'号或密码错误');
            }
            $user = $this->container->auth->attempt($params['username'],$params['password'],$params['type']);
        }else{
            return $this->json(-103,'登录类型错误');
        }
        if($user){
            $result = $this->container->auth->generateToken($user);
            $data   = $this->container->fractal->createData(new Item($result,new UserTransformer()))->toArray();
            return $this->jsonWithData(1,'OK', $data);
        }
        return $this->json(0,'登录失败');
    }

    protected function validateRequest($values,$type){
        if($type==1){
            return $this->container->validator->validateArray($values,
                [
                    'phone' => v::noWhitespace()->phone()->notEmpty()->setTemplate('请正确填写手机号码'),
                    'code' => v::noWhitespace()->notEmpty()->setTemplate('请正确填写手机验证码'),
                ]);
        }else if($type==2){
            return $this->container->validator->validateArray($values,
                [
                    'username' => v::noWhitespace()->notEmpty()->setTemplate('请填写用户名'),
                    'password' => v::noWhitespace()->notEmpty()->setTemplate('请填写秘密'),
                ]);
        }

    }
}